﻿using Domain;
using Newtonsoft.Json;
using Utils;

namespace Business
{
    /// <summary>
    /// sso 认证中心
    /// </summary>
    public class Oauth
    {
        //得到redis连接字符
        public static string _ReidsConne { get { return AppConfigurtaionServices.Configuration["Appsettings:RedisConnection"]; } }
        RedisHelper redisHelper = new RedisHelper(_ReidsConne);

        /// <summary>
        /// 验证token
        /// </summary>
        /// <param name="TokenValue">token值</param>
        /// <returns></returns>
        public OperateStatus<user> VerifyLogin(string TokenValue)
        {
            OperateStatus<user> operateStatus = new OperateStatus<user>();
            if (!string.IsNullOrWhiteSpace(TokenValue))
            {
                //根据cookies值得到用户名和密码
                var jsonData = DEncryptStatus.Base64Decrypt(TokenValue);
                var user = JsonConvert.DeserializeObject<user>(jsonData);
                //根据用户名和密码得到redis里面的token 值
                string tokenName = DEncryptStatus.Base64Encrypt(user.UserName + user.UserId);
                var redisTokenValue = redisHelper.GetValue(tokenName).ToString();
                if (!string.IsNullOrWhiteSpace(redisTokenValue))
                {
                    //如果传过来的token和redis里的token一样
                    if (redisTokenValue.Trim('"') == TokenValue)
                    {
                        operateStatus.ResultSign = ResultSign.Successful;
                        operateStatus.Data = user;
                    }
                    else
                    {
                        operateStatus.ResultSign = ResultSign.Error;
                    }
                }
                else
                {
                    operateStatus.ResultSign = ResultSign.Error;
                }
                //var token = redisHelper.GetValue(CookiesToken);
            }
            else
            {
                operateStatus.ResultSign = ResultSign.Error;
            }
            return operateStatus;
        }

        /// <summary>
        /// 用户实体
        /// </summary>
        public class user
        {
            /// <summary>
            /// 用户名
            /// </summary>
            public string UserName { get; set; }

            /// <summary>
            /// 密码
            /// </summary>
            public string Password { get; set; }

            /// <summary>
            /// 用户id
            /// </summary>
            public string UserId { get; set; }
        }
    }
}
